package com.iloomo.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;

/**
 * 说明：Redis 简单工具类
 * 创建人：
 * 修改时间：2019年04月27日
 * @version
 */
@Component
public class RedisUtil {

	private static String staticHost;
	private static String staticPassword;
	private static int staticPort;
	private static int staticTimeout;
	private static int staticMaxActive;
	private static int staticMaxIdle;
	private static int staticMinIdle;
	private static long staticMaxWaitMillis;

	@Value("${spring.redis.host}")
	private String host;
	@Value("${spring.redis.password}")
	private String password;
	@Value("${spring.redis.port}")
	private int port;
	@Value("${spring.redis.timeout}")
	private int timeout;
	@Value("${spring.redis.jedis.pool.max-active}")
	private int maxActive;
	@Value("${spring.redis.jedis.pool.max-idle}")
	private int maxIdle;
	@Value("${spring.redis.jedis.pool.min-idle}")
	private int minIdle;
	@Value("${spring.redis.jedis.pool.max-wait}")
	private long maxWaitMillis;

	@PostConstruct
	public void getHost() {
		staticHost = this.host;
	}
	public static String getStaticHost() {
		return staticHost;
	}
	@PostConstruct
	public void getPassword() {
		staticPassword = this.password;
	}
	@PostConstruct
	public void getPort() {
		staticPort = this.port;
	}
	@PostConstruct
	public void getTimeout() {
		staticTimeout = this.timeout;
	}
	@PostConstruct
	public void getMaxActive() {
		staticMaxActive = this.maxActive;
	}
	@PostConstruct
	public void getMaxIdle() {
		staticMaxIdle = this.maxIdle;
	}
	@PostConstruct
	public void getMinIdle() {
		staticMinIdle = this.minIdle;
	}
	@PostConstruct
	public void getMaxWaitMillis() {
		staticMaxWaitMillis = this.maxWaitMillis;
	}
	private static JedisPool pool = null;


	/**
	 * 构建redis连接池
	 * @return JedisPool
	 */
	public static JedisPool getPool() {
		if (pool == null) {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(500);
			//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
			config.setMaxIdle(5);
			//表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；
			config.setMaxWaitMillis(1000 * 100);
			//在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
			config.setTestOnBorrow(true);
			pool = new JedisPool(config, staticHost,staticPort,staticTimeout,staticPassword);
		}
		return pool;
	}

	/**
	 * 获取jedis对象
	 * @return Jedis 返回jedis对象
	 */
	public static Jedis getJedis(){
		JedisPool pool = getPool();;
		Jedis jedis = pool.getResource();
		return jedis;
	}

	/**
	 * 返还到连接池
	 *
	 * @param pool
	 * @param redis
	 */
	public static void returnResource(JedisPool pool, Jedis redis) {
		if (redis != null) {
			pool.returnResource(redis);
		}
	}

	/**
	 * 设置字符串值到redis，key为传入的值
	 * @param key		传入的key值
	 * @param value		 设置到redis的值
	 * @param isExpire	 是否设置实效时间
	 * @param seconds	 失效时间（单位：秒）
	 * @return			 返回key值
	 */
	public static String setKeyAndString(String key,String value,boolean isExpire,int seconds){
		Jedis jedis = null;
		try {

			jedis = getJedis();
			jedis.set(key, value);
			if(isExpire){
				jedis.expire(key, seconds);
			}
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			key = "";
		} finally {
			//返还到连接池
			returnResource(pool,jedis);
		}
		return key;
	}

	/**
	 * 获取数据
	 *
	 * @param key
	 * @return
	 */
	public static String get(String key){
		String value = null;

		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = getPool();
			jedis = pool.getResource();
			value = jedis.get(key);
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}

		return value;
	}

	//在redis中放入用户值
	public static String addtoKen(String userid){
		JedisPool pool = null;
		Jedis jedis = null;
		String token=UuidUtil.get32UUID();
		try {
			pool = getPool();
			jedis = pool.getResource();
			jedis.set(token, userid);
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
			token = "";
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}
		return token;
	}

	//检测redis中的某Key是否存在
	public static Boolean exitToken(String key){
		JedisPool pool = null;
		Jedis jedis = null;
		Boolean keyFlag = false;
		try {
			pool = getPool();
			jedis = pool.getResource();
			keyFlag = jedis.exists(key);
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}
		return keyFlag;
	}

	//获取对应Key的值
	public static String getToKen(String key){
		JedisPool pool = null;
		Jedis jedis = null;
		String value="";
		try {
			pool = getPool();
			jedis = pool.getResource();
			value = jedis.get(key);
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}
		return value;
	}

	//删除对应Key的值
	public static void  del(String key){
		JedisPool pool = null;
		Jedis jedis = null;
		String value="";
		try {
			pool = getPool();
			jedis = pool.getResource();
			jedis.del(key);
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}
	}

	//根据token获取值
	public static String getvalue(String token,String key){
		JedisPool pool = null;
		Jedis jedis = null;
		String value="";
		try {
			pool = getPool();
			jedis = pool.getResource();
			value=jedis.hmget(token,key).get(0);

		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}
		return value;
	}

	/**
	 * 添加hashmap及超时时间
	 * @param key
	 * @param seconds
	 */
	public static void addHash(String key,int seconds,Map<String,String> hash) {
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = getPool();
			jedis = pool.getResource();
			jedis.hmset(key, hash);
			jedis.expire(key, seconds);
		} catch (Exception e) {
			// 释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			// 返还到连接池
			returnResource(pool, jedis);
		}
	}

	/**
	 * 设置hashmap
	 * @param key
	 * @param hash
	 */
	public static void setHash(String key,Map<String,String> hash) {
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = getPool();
			jedis = pool.getResource();
			jedis.hmset(key, hash);
		} catch (Exception e) {
			// 释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			// 返还到连接池
			returnResource(pool, jedis);
		}
	}

	/**
	 * 根据key获取hashmap
	 * @param key
	 * @return
	 */
	public static Map<String,String> getHash(String key){
		Map<String,String> hash = null;

		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = getPool();
			jedis = pool.getResource();
			hash = jedis.hgetAll(key);
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}

		return hash;
	}

	/**
	 * 模糊查询所有keys
	 * @param key
	 * @return
	 */
	public static Set<String> getKeys(String key){
		Set<String> keys = null;

		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = getPool();
			jedis = pool.getResource();
			keys = jedis.keys(key+"*");
		} catch (Exception e) {
			//释放redis对象
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			//返还到连接池
			returnResource(pool, jedis);
		}

		return keys;
	}

	public static void main(String[] args) {
		getvalue("8789e80928f44056a191224b1f05eafc","id");
		System.out.println(getvalue("8789e80928f44056a191224b1f05eafc","id"));
	}
}
